#include "precomp.h"
#include <ServerEngine/File/FileSystem.h>

using namespace TSE;

FileSystem::FileSystem(Engine &engine)
: engine(engine), initialized(false)
{
	vfs = CL_VirtualFileSystem(CL_System::get_exe_path(), false);
	if(vfs.is_null())
		return;

	vdir = vfs.get_root_directory();
	initialized = true;
}

FileSystem::~FileSystem()
{
}

CL_String FileSystem::getRootPath()
{
	if(!initialized)
		return CL_String();

	return vfs.get_provider()->get_path();
}

std::vector<CL_String> FileSystem::getFilesInDir(const CL_String &rel_dir)
{
	std::vector<CL_String> files;
	if(!initialized)
		return files;

	CL_VirtualDirectory vdirWithFiles = vdir.open_directory(rel_dir);
	CL_VirtualDirectoryListing vdir_list = vdirWithFiles.get_directory_listing();
	while(vdir_list.next())
	{
		if(vdir_list.is_directory())
			continue;
		if(!vdir_list.is_readable())
			continue;
		if(vdir_list.get_filename().empty())
			continue;

		files.push_back(vdir_list.get_filename());
	}
	return files;
}

CL_String FileSystem::getContentInFile(const CL_String &rel_dir, const CL_String &file)
{
	if(!initialized)
		return CL_String();

	CL_VirtualDirectory vdirWithFiles = vdir.open_directory(rel_dir);
	CL_IODevice device = vdirWithFiles.open_file_read(file);
	if(device.is_null())
		return CL_String();

	CL_String content = device.read_string_text("", "\0");
	return content;
}
